package com.berg.metroarrived;

import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.SimpleCursorAdapter.ViewBinder;

import com.berg.metroarrived.StationDB.StationsColumns;




public class StationsList extends ListActivity   {
	private static final String DTAG = "locations";
	private TextView selection;
	private static final int URL_LOADER = 1;
	
	//private List<String> mCellIds =new  ArrayList<String>();
	//private List<String> mNames = new  ArrayList<String>();
	
	 /**
     * The columns we are interested in from the database
     */
    private final static String[] PROJECTION = new String[] {
    	StationsColumns._ID, // 0
    	StationsColumns.NAME, // 1
    	StationsColumns.ENABLED, // 2
    };
    
    private final static int COLUMN_INDEX_NAME = 1;
    private final static int COLUMN_INDEX_ENABLED = 2;
    
	
	LoaderManager.LoaderCallbacks<Cursor> loaderCb= 
			new LoaderManager.LoaderCallbacks<Cursor>(){
		/*
		* Callback that's invoked when the system has initialized the Loader and
		* is ready to start the query. This usually happens when initLoader() is
		* called. The loaderID argument contains the ID value passed to the
		* initLoader() call.
		*/
		@Override
		public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle)
		{
		    /*
		     * Takes action based on the ID of the Loader that's being created
		     */
		    switch (loaderID) {
		        	case URL_LOADER:
		            // Returns a new CursorLoader
		            return new CursorLoader(
		            			StationsList.this,   // Parent activity context
		                        StationsColumns.CONTENT_URI,        // Table to query
		                        PROJECTION,     // Projection to return
		                        null,            // No selection clause
		                        null,            // No selection arguments
		                        null             // Default sort order
		        );
		        default:
		            // An invalid id was passed in
		            return null;
		    }
		}
		
		/*
		 * Defines the callback that CursorLoader calls
		 * when it's finished its query
		 */
		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
			
			//mCellIds.clear();
			//mNames.clear();
			
			Log.d(DTAG,"cursor size is:" + cursor.getCount());
			
//			ListView lv = getListView();
//			cursor.moveToFirst();
//			for(int i = 0;i < cursor.getCount();i++,cursor.moveToNext()){
//				Log.d(DTAG," checkd " + cursor.getString(2));
//			//	boolean checked = cursor.getString(2).equals("1"); 
//			//	lv.setItemChecked(i, checked);
//			}
			mAdapter.swapCursor(cursor);
			

		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
			// TODO Auto-generated method stub
			mAdapter.swapCursor(null);
			
		}
		
	};
	
	SimpleCursorAdapter.ViewBinder vb = new SimpleCursorAdapter.ViewBinder(){
		 public boolean setViewValue(View view, Cursor cursor, int columnIndex){
			 if(columnIndex != COLUMN_INDEX_ENABLED) 
				 return false;
			 boolean checked = cursor.getString(columnIndex).equals("1");
			 ListView lv = getListView();
			 lv.setItemChecked(cursor.getPosition(), checked);
			 Log.d("DTAG","position " +cursor.getPosition() + " " + String.valueOf(checked)+ " " +cursor.getString(0) + " " + cursor.getString(1));
			 return true;
		 }
	};

    /** The index of the title column */
   // private static final int COLUMN_INDEX_TITLE = 1;
    private SimpleCursorAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_locations);
		
		// Create a new adapter and bind it to the List View
		mAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_multiple_choice, null,
				new String[] { StationsColumns.NAME,StationsColumns.ENABLED},
				new int[] { android.R.id.text1,android.R.id.text1}, 0);
		mAdapter.setViewBinder(vb);
		setListAdapter(mAdapter);

		//setListAdapter(new ArrayAdapter<String>(this,
		//		android.R.layout.simple_list_item_1, items));
		
		// Initiate the Cursor Loader
		//getLoaderManager().initLoader(0, null, this);
		
		
		selection = (TextView) findViewById(R.id.selection);
		
		//  setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

	        // If no data was given in the intent (because we were started
	        // as a MAIN activity), then use our default content provider.
	        Intent intent = getIntent();
	        if (intent.getData() == null) {
	            intent.setData(StationsColumns.CONTENT_URI);
	        }

        // Inform the list we provide context menus for items
        getListView().setOnCreateContextMenuListener(this);
        
        //set the multichoice mode
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        /*
         * Initializes the CursorLoader. The URL_LOADER value is eventually passed
         * to onCreateLoader().
         */
        getLoaderManager().initLoader(URL_LOADER, null, loaderCb);
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		getLoaderManager().restartLoader(URL_LOADER, null, loaderCb);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		Log.i(DTAG,"position = " + position);
       
		Cursor cursor = (Cursor) getListAdapter().getItem(position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }
        selection.setText(cursor.getString(COLUMN_INDEX_NAME));
        
        boolean checked = l.isItemChecked(position);

        
        //update the filed:enabled
        Uri selectUri  = ContentUris.withAppendedId(StationsColumns.CONTENT_URI, id);
        ContentResolver cr = this.getContentResolver();
        ContentValues cv =  new ContentValues();
        cv.put(StationsColumns.ENABLED, checked?"1":"0");
        Log.d(DTAG,"update url = " + selectUri.toString() + " item = " + cv.toString() );
        cr.update(selectUri, cv, null, null);
        
		
//		Uri selectUri  = ContentUris.withAppendedId(StationsColumns.CONTENT_URI, id);
//		Intent i = new Intent(this, StationInfo.class);
//		i.setAction(Intent.ACTION_VIEW);
//		i.setData(selectUri);
//		startActivity(i);
	
	}
	
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_options_menu, menu);
        // Generate any additional actions that can be performed on the
        // overall list.  In a normal install, there are no additional
        // actions found here, but this allows other applications to extend
        // our menu with their own actions.
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, StationsList.class), null, intent, 0, null);

        return super.onCreateOptionsMenu(menu);
    }
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_add:
            // Launch activity to insert a new item
            startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            Log.e(DTAG, "bad menuInfo", e);
            return;
        }

        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_context_menu, menu);
        
        // Set the context menu header
        menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_NAME));
        
        // Append to the
        // menu items for any other activities that can do stuff with it
        // as well.  This does a query on the system for any activities that
        // implement the ALTERNATIVE_ACTION for our data, adding a menu item
        // for each one that is found.
        Intent intent = new Intent(null, Uri.withAppendedPath(getIntent().getData(), 
                                        Integer.toString((int) info.id) ));
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, StationsList.class), null, intent, 0, null);
    }
	
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            Log.e(DTAG, "bad menuInfo", e);
            return false;
        }
        
        Uri stationUri = ContentUris.withAppendedId(getIntent().getData(), info.id);

        switch (item.getItemId()) {
        case R.id.context_open:
            // Launch activity to view/edit the currently selected item
            startActivity(new Intent(Intent.ACTION_EDIT, stationUri));
            return true;
        case R.id.context_delete:
            // Delete the note that the context menu is for
            getContentResolver().delete(stationUri, null, null);
            return true;
        default:
            return super.onContextItemSelected(item);
        }
    }

}
